package com.jeesite.modules.sd.common.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.nio.charset.Charset;

/**
 * HttpClient工具类
 */
@Slf4j
public class HttpUtil {

    /**
     * 发送JSON格式
     *
     * @param url   地址
     * @param param json参数
     * @return
     */
    public static String executeUrlOfJson(String url, JSONObject param) {
        HttpPost httpPost;
        String result = null;
        try {
            HttpClient client = new DefaultHttpClient();
            httpPost = new HttpPost(url);
            if (param != null) {
                StringEntity se = new StringEntity(param.toString(), "utf-8");
                // post方法中，加入json数据
                httpPost.setEntity(se);
                httpPost.setHeader("Content-Type", "application/json");
//                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            }

            HttpResponse response = client.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "utf-8");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    /**
     * 发送文件
     *
     * @param url     地址
     * @param builder 文件对象
     * @return
     */
    public static String executeUrlOfBuilder(String url, MultipartEntityBuilder builder) {
        HttpPost httpPost;
        String result = null;
        try {
            HttpClient client = new DefaultHttpClient();
            httpPost = new HttpPost(url);
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            //执行提交
            HttpResponse response = client.execute(httpPost);
            Header[] allHeaders = response.getAllHeaders();
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                //将响应的内容转换成字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));

                //此处根据服务器返回的参数转换，这里返回的是JSON格式
                JSONObject output = JSON.parseObject(result);
                String msg = output.get("msg").toString();
                String data = output.get("data").toString();

                log.info(msg);
                log.info(data);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }
}
